﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls.Maps;
using Facebook;


namespace AOuSuisJeWP7
{
    public partial class NewEnigma : PhoneApplicationPage
    {
        private readonly CameraCaptureTask  ctask;

        ApplicationBarIconButton btnCamera;
        ApplicationBarIconButton btnCheck;
        ApplicationBarIconButton btnRefreshPosition;

        public NewEnigmaViewModel ViewModel { get { return DataContext as NewEnigmaViewModel; } }

        public NewEnigma()
        {
            InitializeComponent();
            ctask = new CameraCaptureTask();
            ctask.Completed += ctask_Completed;
            DataContext = new NewEnigmaViewModel();

            btnCamera = new ApplicationBarIconButton(new Uri("/icons/appbar.feature.camera.rest.png", UriKind.Relative));
            btnCamera.Click += new EventHandler(btnCamera_Click);
            btnCamera.Text = "Take Pic";

            btnCheck = new ApplicationBarIconButton(new Uri("/icons/appbar.check.rest.png", UriKind.Relative));
            btnCheck.Click += new EventHandler(btnCheck_Click);
            btnCheck.Text = "Post Enigma";

            btnRefreshPosition = new ApplicationBarIconButton(new Uri("/icons/appbar.refresh.rest.png", UriKind.Relative));
            btnRefreshPosition.Click += new EventHandler(btnRefreshPosition_Click);
            btnRefreshPosition.Text = "Localize";

            ViewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ViewModel_PropertyChanged);

            ((App)Application.Current).CurrentDataContext = DataContext;
            initMap();
        }

        void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (ViewModel.Position != null)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    Map.SetView(ViewModel.Position, 15);
                    MyPp.Location = ViewModel.Position;
                    MyPp.Visibility = System.Windows.Visibility.Visible;
                });
            }
            //e.PropertyName.Equals("Position") && ViewModel.Position != null
            //    &&
            if ( !ApplicationBar.Buttons.Contains(btnCheck))
            {
                ApplicationBar.Buttons.Clear();
                ApplicationBar.Buttons.Add(btnCheck);
            }
        }
        void PublishOnFb()
        {
            var token = ((App)App.Current).userLogin.FbToken;
            FacebookClient Fc= new FacebookClient(token);
            //Fc.PostAsync();
        }

        void btnCheck_Click(object sender, EventArgs e)
        {
            if (!ViewModel.Validate())
            {
                if (ViewModel.ValidationErrors.Contains("CapturedImage"))
                {
                    PivotContainer.SelectedItem = picItem;
                    ViewModel.StatusText = "A valid picture should be taken";
                }
                else if (ViewModel.ValidationErrors.Contains("Title"))
                {
                    PivotContainer.SelectedItem = infoItem;
                    ViewModel.StatusText = "A valid title should be specified";
                }
                else if (ViewModel.ValidationErrors.Contains("Position"))
                {
                    PivotContainer.SelectedItem = geoItem;
                    ViewModel.StatusText = "A valid enigma position should be specified";
                }
            }
            else
            {
                PostEnigma();
            }
        }
        public void PostEnigma()
        {

            // appel de ousuisjeService en rest
            AOuSuisJe.ApiUpload api = new AOuSuisJe.ApiUpload();


            ViewModel.StatusText = "Upload de la Photo.";
            //uploadphoto
            if(ViewModel.IdEnigma==Guid.Empty)
                ViewModel.IdEnigma = Guid.NewGuid();
            api.ApiCallEnded += new AOuSuisJe.ApiCallEndedEventHandler(api_ApiCallEndedPhotoUpload);
            api.Upload(ViewModel.IdEnigma.ToString(), ViewModel.StrPhoto);

        }

        void api_ApiCallEndedPhotoUpload(object sender, EventArgs e)
        {
             Dispatcher.BeginInvoke(() =>
                {
                    ViewModel.StatusText = "Upload de la Photo terminé. Création de l'énigme";
                    CreateEnig(); 
                    
                });
            

        }
        void CreateEnig()
        {
            AOuSuisJe.ApiUpload api = new AOuSuisJe.ApiUpload();
            api.CreateEnigma(new AOuSuisJe.Enigma()
            {
                Id=ViewModel.IdEnigma,
                Name = ViewModel.Title,
                Latitude = ViewModel.Position.Latitude,
                Longitude =ViewModel.Position.Longitude,
                Comments = ViewModel.Description
            });
            api.ApiCallEnded += new AOuSuisJe.ApiCallEndedEventHandler(api_ApiCallEndedEnigCreated);
        }
        void api_ApiCallEndedEnigCreated(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                ViewModel.StatusText = "Enigme créé";
            });
        }

        void btnRefreshPosition_Click(object sender, EventArgs e)
        {
            ViewModel.FindPosition();
            
        }

        void initCamera()
        {
        
        }

        void initMap()
        {
            Map.Mode = new RoadMode();
        }

        void btnCamera_Click(object sender, EventArgs e)
        {
            ViewModel.StatusText = "";

            //ViewModel.StrPhoto = App.GetResourceStream(new Uri("WP_000056.jpg",UriKind.Relative)).Stream;
            //ViewModel.CapturedImage = PictureDecoder.DecodeJpeg(ViewModel.StrPhoto);
            ctask.Show();
            //ViewModel.ProgressBarVisibility = Visibility.Visible;
        }

        void ctask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
            {
                ViewModel.HandleCapture(e.ChosenPhoto);
                ViewModel.ProgressBarVisibility = Visibility.Collapsed;
            }
            else
            {
                ViewModel.StatusText = "You decided not to take a picture.";
            }
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ViewModel.StatusText = String.Empty;

            if (e.RemovedItems.Count > 0 && e.RemovedItems[0] != null && e.RemovedItems[0].Equals(picItem))
            {
                ApplicationBar.Buttons.Remove(btnCamera);
            }
            else if (e.AddedItems[0].Equals(picItem))
            {
                ApplicationBar.Buttons.Add(btnCamera);
                ViewModel.StatusText = "Tap the camera button to take a picture.";
            }

            if (e.RemovedItems.Count > 0 && e.RemovedItems[0] != null && e.RemovedItems[0].Equals(geoItem))
            {
                ApplicationBar.Buttons.Remove(btnRefreshPosition);
            }
            else if (e.AddedItems[0].Equals(geoItem))
            {
                ApplicationBar.Buttons.Add(btnRefreshPosition);
            }
        }
    }
}